
#include "member_BTorus.h"

using namespace BWE;

member_BTorus::member_BTorus(BTorus* torus)
{
	boss = torus;
	radius = 1;
	outerRadius = 0.1f;
	side = 12;
	divide = 24;
	boss->dirty();
}
member_BTorus::~member_BTorus()
{

}

bool member_BTorus::rebuild()
{
	if (coses.size() != side || sines.size() != side)
	{
		coses.resize(side);
		sines.resize(side);
		for (int i = 0; i <= side; i++)
		{
			double angle = i * PI / side * 2;
			coses[i] = (float)cos(angle);
			sines[i] = (float)sin(angle);
		}
	}
	int numVerts = (side + 1) * (divide + 1);
	int numFaces = side * divide * 2;
	BVectorArray* vertices = boss->vertices();
	BVectorArray* normals = boss->normals();
	BCoordArray* texCoords = boss->texCoords();
	BFaceArray* faces = boss->faces();
	if (!vertices || vertices->size() != numVerts)
	{
		vertices = new BVectorArray(numVerts);
		normals = new BVectorArray(numVerts);
		texCoords = new BCoordArray(numVerts);
		faces = new BFaceArray(numFaces);
		boss->setVertices(vertices);
		boss->setNormals(normals);
		boss->setTexCoords(texCoords);
		boss->setFaces(faces);
	}

	int vi = 0;
	float sth = 1.0f / side;
	float stv = 1.0f / divide;
	float length = 2 * PI * radius;
	float sh = length / divide;
	for (int j = 0; j <= divide; j++)
	{
		float z = sh * j;
		float tv = 1.0f - stv * j;
		for (int i = 0; i <= side; i++)
		{
			float x = coses[i] * radius;
			float y = sines[i] * radius;
			(*vertices)[vi + i] = BVector(x, y, z);
			(*normals)[vi + i] = BVector(coses[i], sines[i], 0);
			(*texCoords)[vi + i] = BCoord(i * sth, tv);
		}
		vi += side + 1;
	}

	//build faces
	int vs = 0;
	int fi = 0;
	for (int j = 0; j < divide; j++)
	{
		for (int i = 0; i < side; i++)
		{
			int index0 = vs + i;
			int index1 = vs + i + 1;
			int index2 = index0 + side + 1;
			int index3 = index1 + side + 1;
			faces->set(fi, BFace(index0, index1, index3));
			faces->set(fi + 1, BFace(index0, index3, index2));
			fi += 2;
		}
		vs += side + 1;
	}

	return true;
}
